/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, {useState} from 'react';

import Home from './Home';
import Learn from './Learn';

import {
  Text,
  StyleSheet,
  SafeAreaView,
  StatusBar,
  BackHandler,
  Alert,
  Button,
  View,
  Image,
  TextInput,
  ScrollView,
} from 'react-native';
import {NativeRouter, Route, Link} from 'react-router-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import Orientation from 'react-native-orientation-locker';
import TestModel from './TestModel';

export const AppContext = React.createContext({
  statusBar: false,
  setStatusBar() {},
});

class App extends React.Component {
  constructor(props) {
    super(props);

    // State 也包含了更新函数，因此它会被传递进 context provider。
    this.state = {
      value: 'Useless Placeholder',
      statusBar: false,
      setStatusBar: () => {},
    };
  }

  componentDidMount() {
    this.setState(() => ({
      setStatusBar: this.setStatusBar,
    }));
    const initial = Orientation.getInitialOrientation();
    if (initial === 'PORTRAIT') {
      console.log(initial);
    } else {
      console.log(initial);
    }

    BackHandler.addEventListener('hardwareBackPress', () => {
      Alert.alert('?', '?????');
      return !this.state.statusBar;
    });
    // this locks the view to Portrait Mode
    Orientation.lockToPortrait();

    Orientation.getAutoRotateState((rotationLock) => {
      console.log('rotationLock: ', rotationLock);
    });

    // this locks the view to Landscape Mode
    // Orientation.lockToLandscape();

    // this unlocks any previous locks to all Orientations
    // Orientation.unlockAllOrientations();
    Orientation.addOrientationListener(this._orientationDidChange);
  }

  _orientationDidChange = (orientation) => {
    console.log(orientation);
    if (orientation.includes('LANDSCAPE')) {
      // do something with landscape layout
      this.setStatusBar(true);
    } else {
      // do something with portrait layout
      this.setStatusBar(false);
    }
  };

  setStatusBar = (statusBar) => {
    if (statusBar) {
      Orientation.lockToLandscapeLeft();
    } else {
      Orientation.lockToPortrait();
    }
    this.setState(() => ({statusBar}));
  };

  onChangeText = (value) => {
    this.setState(() => ({value}));
  };

  componentWillUnmount() {
    Orientation.getOrientation((err, orientation) => {
      console.log(`Current Device Orientation: ${orientation}`);
    });

    // Remember to remove listener
    Orientation.removeOrientationListener(this._orientationDidChange);
  }

  render() {
    return (
      <AppContext.Provider value={this.state}>
        <NativeRouter>
          <StatusBar hidden={this.state.statusBar} barStyle="dark-content" />
          <SafeAreaView style={styles.safeArea}>
            <View style={styles.home}>
              <Home />
            </View>
            <ScrollView
              style={this.state.statusBar ? {display: 'none'} : styles.other}>
              <Link to="/home">
                <Text style={styles.appLink}>Home</Text>
              </Link>
              <Link to="/learn">
                <Text style={styles.appLink}>Learn</Text>
              </Link>
              <TextInput
                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                onChangeText={(text) => this.onChangeText(text)}
                secureTextEntry
                value={this.state.value}
              />
              <TestModel message={this.state.value} />
              <Image
                // style={styles.tinyLogo}
                source={require('./tiny_logo.png')}
              />
              <Image
                style={styles.tinyLogo}
                source={{
                  uri: 'https://reactnative.dev/img/tiny_logo.png',
                }}
              />
              <Image
                style={styles.tinyLogo}
                source={{
                  uri:
                    '',
                }}
              />
            </ScrollView>
          </SafeAreaView>

          <Route exact path="/home" component={Home} />
          <Route path="/learn" component={Learn} />
        </NativeRouter>
      </AppContext.Provider>
    );
  }
}

const styles = StyleSheet.create({
  appLink: {
    padding: 10,
    color: Colors.primary,
  },
  safeArea: {
    flex: 1,
  },
  tinyLogo: {
    margin: 20,
    width: 100,
    height: 100,
  },
  home: {
    flex: 4,
  },
  other: {
    flex: 1,
  },
});

export default App;
